﻿package com.edward.service;


import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.edward.PagerModel;
import com.edward.model.Client;

public class ClientManager extends HibernateDaoSupport {
	
	private JdbcTemplate jdbcTemplate;
	
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public void addClient(Client client) {
		
		getHibernateTemplate().save(client);
	}
	
	public Client getClient(int id){
		Client c =(Client)getHibernateTemplate().get(Client.class, id);
		return c;
	}
	

	@SuppressWarnings("unchecked")
	public List<Client> listClient() {
		return getHibernateTemplate().find("from Client");
	}
	
	@SuppressWarnings("unchecked")
	public PagerModel pagerClient(int start,int limit) {
		int total = getHibernateTemplate().find("from Client").size();
		int toIndex = start + limit;
		if(toIndex>total){
			toIndex =  total;
		}
		List <Client>datas = getHibernateTemplate().find("from Client").subList(start, toIndex);
		PagerModel pm = new PagerModel();
		pm.setTotal(total);
		pm.setDatas(datas);
		return pm;
		
	}
	
	@SuppressWarnings("unchecked")
	public PagerModel pagerClient(int start,int limit,Client client) {
		int count = 0;
		String sql = "from Client c where ";
		if(!client.getCompany().equals("")){
			sql += "c.name = '" + client.getCompany() + "'";
			count++;
		}
	
		
		int total = getHibernateTemplate().find(sql).size();
		int toIndex = start + limit;
		if(toIndex>total){
			toIndex =  total;
		}
		List <Client>datas = getHibernateTemplate().find(sql).subList(start, toIndex);
		PagerModel pm = new PagerModel();
		pm.setTotal(total);
		pm.setDatas(datas);
		return pm;
		
	}
	
	public void updateClient(Client client) {
	
		getHibernateTemplate().update(client);
	}
	
	public void deleteClient(int id){
		
		getHibernateTemplate().delete(getClient(id));
	}
	
	@SuppressWarnings("unchecked")
	public List getClients(String query) {
		String sql = "select  distinct c.company from client c where c.company like '%" + query + "%'" ;
		List list = jdbcTemplate.queryForList(sql);
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public Client getClient(String query) {
		List<Client> list = getHibernateTemplate().find(
				"from Client c where c.company like '" + query + "'");
		if(list.size()>0){
		Client c = list.get(0);
			return c;
		}else{
			return null;
		}
		
	}
	
	//检查有没同名称或者编号的货物
	@SuppressWarnings("unchecked")
	public Client check(String query) {
		List<Client> list = getHibernateTemplate().find(
				"from Client c where c.company = '" + query + "'");
		if(list.size()>0){
			return list.get(0);
		}
		return null;

	}


}



